import * as os from "os";
import * as path from "path";
import * as fs from "fs";

type MySqlInfo = {
  host: string;
  port: number;
  username: string;
  password: string;
  database?: string;
};

/**
 * 获取MySQL信息
 * @returns
 */
// 导出一个函数，用于获取MySQL信息
export function getMySqlInfo(): MySqlInfo {
  // 获取当前用户的主目录
  const homedir = os.homedir();
  // 获取MySQL信息的文件路径
  const usernamePath = path.resolve(homedir, "vben", "mysql.json");
  // 读取MySQL信息文件
  const mysqlInfo = fs.readFileSync(usernamePath, "utf-8");
  // 将MySQL信息文件解析为JSON格式
  return JSON.parse(mysqlInfo);
}

/**
 * 对接口的相应进行封装
 * @param data
 * @param message
 * @returns
 */
export function success<T>(data: T, message: string = "success"): { code: number, data: T, message: string } {
  return {
    code: 200,
    data,
    message
  }
}


export function error<T>(message: string = "error"): { code: number, message: string } {
  return {
    code: 500,
    message
  }
}

export function warappResponse<T>(data: Promise<T>, message: string): Promise<{
    code: number;
    data: T;
    message: string;
}> {
  return data.then((res: T) => success(res, message)).catch(err => error(err.message))
}
